<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\Console;
use yii\helpers\ArrayHelper;

/**
 * 初始化类型数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200105_001100_d_resident extends Migration {

    /**
     * @var string 临时增加内存
     */
    public $memorySize = '512M';

    /**
     * @inheritdoc
     */
    public $tableName = '{{%resident}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->truncateTable($this->tableName);
        $this->compact = true;
        $string = $this->getData('resident.txt');
        $data = explode("\n", $string);
        $count = count($data);
        Console::startProgress($i = 0, $count);
        foreach ($data as $item) {
            if (!$item) {
                continue;
            }
            $columns = explode("\t", $item);
            if (empty($columns) || count($columns) !== 4) {
                continue;
            }
            //马新明	370921194911170055	八仙桥街道红庙村263号	13562845329
            $attributes = array_combine(['realname', 'idcardno', 'address', 'mobile'], $columns);
            $i++;
            Console::updateProgress($i, $count);
            $resident = (new Query())->from($this->tableName)->andWhere(['idcardno' => $attributes['idcardno']])->one();
            if ($resident) {
                $this->update($this->tableName, $attributes, [
                    'id' => $resident['id']
                ]);
            } else {
                $this->insert($this->tableName, ArrayHelper::merge($attributes, [
                    'status' => 10,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]));
            }
        }
        Console::endProgress("update done." . PHP_EOL);
    }

}
